package ch4.DataBasedSeparation;

import util.Tools;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 下载子任务类
 */

public class DownloadTask implements Runnable{
    private final long lowerBound;
    private final long upperBound;
    private final DownLoadBuffer xbuf;
    private final URL requestURL;
    private final AtomicBoolean cancelFlag;

    public DownloadTask(long lowerBound, long upperBound, URL requestURL, Storage storage, AtomicBoolean cancelFlag) {
        this.lowerBound = lowerBound;
        this.upperBound = upperBound;
        this.requestURL = requestURL;
        this.xbuf = new DownLoadBuffer(lowerBound, upperBound, storage);
        this.cancelFlag = cancelFlag;
    }

    // 对指定的URL发起HTTP 分段下载请求
    private static InputStream issueRequest(URL requestURL, long lowerBound, long upperBound) {
        //...
        return new InputStream() {
            @Override
            public int read() throws IOException {
                return 0;
            }
        };
    }

    @Override
    public void run() {
       if (cancelFlag.get()) {
           return;
       }
        ReadableByteChannel channel = null;
       try {
           channel = Channels.newChannel(issueRequest(requestURL, lowerBound, upperBound));
           ByteBuffer buf = ByteBuffer.allocate(1024);
           while (!cancelFlag.get() && channel.read(buf) > 0) {
               // 将从网络读取的数据写入缓冲区
               xbuf.write(buf);
               buf.clear();
           }
       } catch (Exception e) {
           throw new RuntimeException(e);
       } finally {
           Tools.silentClose(channel, xbuf);
       }
    }
}
